package keyfun.utils 
{
	/**
	 * ...
	 * @author Key Hui
	 */
	public class XmlUtil 
	{
		public static function getHeaderString():String
		{
			return '<?xml version="1.0" encoding="UTF-8"?>';
		}
		
		public static function createXML(rootNode:String):XML
		{
			return new XML(<{rootNode} />);
		}
		
		public static function appendChild(xml:XML, child:XML):void
		{
			xml.appendChild(child);
		}
		
		public static function createNodeWithAttributes(rootNode:String, ...args):XML
		{
			if (args.length % 2 != 0)
			{
				trace("Error parameter number!");
				return null;
			}
			
			var xml:XML = createXML(rootNode);
			for (var i:int = 0; i < args.length; i+=2) 
			{
				xml.@[args[i]] = args[i+1];
			}
			return xml;
		}
		
		public static function attrDebug(xml:XML, attrName:String):String
		{
			return (attrName + ":" + xml.@[attrName]);
		}
		
		public static function attrToString(xml:XML, attrName:String):String
		{
			return String(xml.@[attrName]);
		}
		
		public static function attrToNumber(xml:XML, attrName:String):Number
		{
			return Number(xml.@[attrName]);
		}
		
		public static function createXMLWithContent(rootNode:String, content:String):XML
		{
			var xml:XML = <{rootNode}>{cdata(content)}</{rootNode}>;
			return xml;
		}
		
		private static function cdata(data:String):XML 
		{
			return new XML("<![CDATA[" + data + "]]>");
        }
		
		public static function sortByNode(unsortedList:XMLList, nodeToSort:String, sortOptions:Object=null):XMLList
		{
			var orderArray:Array = new Array();
			for (var i:int = 0; i < unsortedList.length(); i++)
			{
				orderArray.push(unsortedList[i]);
			}
			orderArray.sortOn(nodeToSort, sortOptions);
			
			var newList:XMLList = new XMLList();
			for each (var orderItem:XML in orderArray) 
			{
				newList += orderItem;
			}
			//trace(newList.toXMLString());
			return newList;
		}
		
		public static function sortByAttribute(unsortedList:XMLList, attrToSort:String, sortOptions:Object=null):XMLList
		{
			attrToSort = "@" + attrToSort;
			if (sortOptions == null)
			{
				sortOptions = Array.NUMERIC;
			}
			
			var orderArray:Array = new Array();
			var excludeArray:Array = new Array();
			
			for each (var item:XML in unsortedList) 
			{
				if (attrToSort in item)
				{
					orderArray.push(item);
				}
				else 
				{
					excludeArray.push(item);
				}
			}
	
			orderArray.sortOn(attrToSort, sortOptions);
			var newList:XMLList = new XMLList();
			for each (var orderItem:XML in orderArray) newList += orderItem;
			for each (var excludeItem:XML in excludeArray) newList += excludeItem;
			//trace(newList.toXMLString());
			return newList;
		}

	}

}